use daemonize::{Daemonize, Stdio};
use std::fs;
use std::path::Path;

pub fn daemonize(wd: &str, msg: &'static str) {
    let pid_file = Path::new(wd).join("nftp.pid");

    let daemon = Daemonize::new()
        .pid_file(pid_file.as_path())
        .stdout(Stdio::keep())
        .stderr(Stdio::keep())
        .working_directory(wd);

    match daemon.start() {
        Ok(_) => println!("{msg}"),
        Err(e) => {
            let pid = fs::read_to_string(pid_file).unwrap_or("unknown\n".into());
            eprint!("daemonize error: {}, nftp is already running, pid = {}", e, pid);
            std::process::exit(1);
        },
    }
}